//
//  ConnectGatewayController.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/24.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "ConnectGatewayController.h"
#import "ConnectNetwayCell.h"
#import "BindingGatewayView.h"
#import "MQTTCoverTool.h"
#import "MQTTSessionManager.h"
#import "XAIGateway.h"
#import "DataManager.h"
#import "ZTDeviceUtil.h"
#import "ZTLinkageUtil.h"
#import "JPUSHService.h"
#import "MQTTSessionManager.h"
#import "UIView+HUD.h"
#import "GlobalConst.h"
#import <XAISDK/XAIBroadcastPack.h>

static NSString *const kConnectNetwayCellIdentifier = @"kConnectNetwayCellIdentifier";
@interface ConnectGatewayController ()
<
UITableViewDelegate,
UITableViewDataSource,
BindingGatewayViewDelegate
>

@property (nonatomic, strong) UILabel               *topLabel;
@property (nonatomic, strong) UITableView           *m_tableView;
@property (nonatomic, strong) UIButton              *m_btnNext;
@property (nonatomic, strong) NSArray        <XAIBroadcastPack *>*m_gateways;
@property (nonatomic, strong) ConnectNetwayCell   *currentSelectCell;
@property (nonatomic, assign) NSInteger             selectedIndex;
@property (nonatomic, strong) BindingGatewayView  *m_viewBindGateway;
@property (nonatomic, strong) UIView                *m_viewCover;
@property (nonatomic, copy)   NSString              *m_host;
@property (nonatomic, assign) BOOL                  m_boolBind;
@property (nonatomic, strong) XAIGateway             *gateWay;
@property (nonatomic, strong) XAIBroadcastPack*     m_pack;

@end

@implementation ConnectGatewayController


#pragma mark - life cycle

- (void)dealloc
{
    debugLogInfo(@"ConnectGatewayController dealoc...");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self.view yh_showLoadingHUD];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       NSArray* array =  [kMQTTSessionManager.xai gatewayLocalSearch:8000];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (array.count == 0)
            {
                [self.view yh_hideAllHUD];
                [self.view yh_showMsgHUD:@"没有搜索到网关"];
            }
            else
            {
                [self.view yh_hideAllHUD];
                self.m_gateways = array;
                [self.m_tableView reloadData];
            }
        });
    });
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:false animated:true];
}

#pragma mark - event response
- (void)didTappedNextButton
{
    if (self.selectedIndex < 0)
    {
        [self.view yh_showMsgHUD:@"请选择要绑定的网关"];
        return;
    }
    if (self.m_gateways.count == 0) {
        [self.view yh_showMsgHUD:@"没有可选择的网关"];
        return;
    }
    self.m_pack = self.m_gateways[self.selectedIndex];
    if (0 == self.m_pack.flag)
    {
        [self.view yh_showLoadingHUD];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSError*error =  [kMQTTSessionManager.xai bindGatewayWithApsn:self.m_pack.apsn gatewayLuid:0x01 message:@"iOS"];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error.code == 0)
                {
                    [self.view yh_hideAllHUD];
                    [self.view yh_showMsgHUD:@"告知管理员成功，需等到管理员同意"];
                }
                else
                {
                    NSLog(@"%@",error);
                    [self.view yh_hideAllHUD];
                    [self.view yh_showMsgHUD:@"绑定失败"];
                }
                [self.navigationController popToRootViewControllerAnimated:YES];
            });

        });
    }
    else if (self.m_pack.flag == 1)
    {
        [self addBindGatewayView];
    }else if (self.m_pack.flag == 2)
    {
        
    }
}
#pragma mark - BindingNetwayViewDelegate
- (void)sureBtnClick:(NSString *)str
{
    if (str.length < 4) {
        [self.view yh_showMsgHUD:@"网关名称长度不对"];
        [self.m_viewBindGateway removeFromSuperview];
        [self.m_viewCover removeFromSuperview];
        return;
    }
    NSString *strGatewayName = [NSString stringWithFormat:@"%@\0",str];
    XAIBroadcastPack *sendPack = [[XAIBroadcastPack alloc]init];
    sendPack.flag = 2;
    sendPack.apsn = kZTCloudGatewayApsn; //固定值 云网关apsn
    sendPack.luid = kMQTTSessionManager.currentUser.luid;
    sendPack.name = strGatewayName;
    NSData *data = [sendPack toData];
    [self.view yh_showLoadingHUD];
    [kMQTTSessionManager.xai gatewayLocalBind:kMQTTSessionManager.currentUser.m_strTel gatewayIP:self.m_pack.strIP gatewayAPSN:kZTCloudGatewayApsn name:strGatewayName];
    [self.m_viewBindGateway removeFromSuperview];
    [self.m_viewCover removeFromSuperview];
    [self.view yh_hideAllHUD];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = self.m_gateways.count;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ConnectNetwayCell *cell = [tableView dequeueReusableCellWithIdentifier:kConnectNetwayCellIdentifier];
    XAIBroadcastPack *pack = self.m_gateways[indexPath.row];
    cell.title = pack.name;
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndex = indexPath.row;
    ConnectNetwayCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    self.currentSelectCell.selectedView.hidden  = YES;
    cell.selectedView.hidden = NO;
    self.currentSelectCell = cell;
}


#pragma mark - private method 

- (void)setupUI
{
    self.navigationItem.title = @"连接网关";
    [self.view addSubview:self.topLabel];
    [self.view addSubview:self.m_btnNext];
    [self.view addSubview:self.m_tableView];
    [self layoutPageSubviews];
}

- (void)layoutPageSubviews
{
    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.trailing.leading.equalTo(self.view);
        make.height.equalTo(kIphoneSize_Height(41));
    }];

    [self.m_btnNext mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-kIphoneSize_Height(10));
        make.centerX.equalTo(self.view);
        make.width.equalTo(kIphoneSize_Widith(300));
        make.height.equalTo(kIphoneSize_Height(45));
    }];

    [self.m_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topLabel.bottom);
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.m_btnNext.top).offset( - kIphoneSize_Height(10));
    }];
}

- (void)binding:(XAITYPEAPSN)apsn extraInfo:(NSString * __nullable)info
{
    XAIFormatDataCount *formatCount = [[XAIFormatDataCount alloc]init];
    [formatCount addDataType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
     NSData *infoData = [info dataUsingEncoding:NSUTF8StringEncoding];
    [formatCount addDataType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void*) [infoData bytes] length:(int)infoData.length];
    [kMQTTSessionManager sendCmd:0x01 toApsn:kZTCloudGatewayApsn toLuid:kGATEWAYLUID data:formatCount];
}

- (void)addBindGatewayView
{
    [self.view addSubview:self.m_viewCover];
    [self.m_viewCover mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [self.view addSubview:self.m_viewBindGateway];
    [self.m_viewBindGateway mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.height.equalTo(kIphoneSize_Height(200));
        make.width.equalTo(kIphoneSize_Widith(300));
    }];

}

#pragma mark - getters and setters
    
- (UILabel *)topLabel
{
    if (!_topLabel) {
        _topLabel = [[UILabel alloc]init];
        _topLabel.backgroundColor = kBgColor;
        _topLabel.textColor = RGBColor(102, 102, 102);
        _topLabel.text = @"   选择网关";
    }
    return _topLabel;
}

- (UITableView *)m_tableView
{
    if (!_m_tableView) {
        _m_tableView = [[UITableView alloc]init];
        _m_tableView.backgroundColor = kBgColor;
        _m_tableView.delegate = self;
        _m_tableView.dataSource = self;
        _m_tableView.showsVerticalScrollIndicator = NO;
        _m_tableView.showsHorizontalScrollIndicator= NO;
        _m_tableView.rowHeight = kIphoneSize_Height(52);
        [_m_tableView registerClass:[ConnectNetwayCell class] forCellReuseIdentifier:kConnectNetwayCellIdentifier];
        UIView *footerView = [[UIView alloc]init];
        _m_tableView.tableFooterView = footerView;
    }
    return _m_tableView;
}

- (UIButton *)m_btnNext
{
    if (!_m_btnNext) {
        _m_btnNext = [[UIButton alloc]init];
        [_m_btnNext setTitle:@"下一步" forState:UIControlStateNormal];
        [_m_btnNext setBackgroundImage:[UIImage imageNamed:@"scene_circular_bg"] forState:UIControlStateNormal];
        [_m_btnNext addTarget:self action:@selector(didTappedNextButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _m_btnNext;
}

- (NSArray *)m_gateways
{
    if (!_m_gateways) {
        _m_gateways   = [[NSArray alloc]init];
    }
    return _m_gateways;
}

- (UIView *)m_viewCover
{
    if (!_m_viewCover) {
        _m_viewCover = [[UIView alloc]init];
        _m_viewCover.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    }
    return _m_viewCover;
}

- (BindingGatewayView *)m_viewBindGateway
{
    if (!_m_viewBindGateway) {
        _m_viewBindGateway = [[BindingGatewayView alloc]init];
        _m_viewBindGateway.delegate = self;
    }
    return _m_viewBindGateway;
}

@end
